<template>
  <dialog-edit :visible.sync="dialogVisible" :title="$attrs.Title||'新增用例'" ref="userManageEdit" width="1000" :fullscreen="true"
               height="550" @save="save" :saveLoading="saveLoading">
    <template slot="body">
      <el-form class="formBox" style="padding: 10px;"
          ref="form"
          title-width="120"
          label-position="top"
          :data="formData"
          :rules="formRules">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="标题">
              <vxe-input placeholder="请输入标题" v-model="formData.Name" style="width: 100%"></vxe-input>
            </el-form-item>
            <el-form-item label="前置条件">
              <wangeditor placeholder="请输入前置条件" v-model="formData.Preconditions" style="width: 100%"></wangeditor>
            </el-form-item>
            <vxe-grid
                border
                context-menu
                highlight-hover-row
                show-overflow
                resizable
                height="300"
                :edit-config="{trigger: 'click', mode: 'row'}"
                :data.sync="formData.TestCaseStep"
                ref="grid">
              <vxe-table-column field="Sort" title="#" sortable width="100">
                <template #default="{ row }">
                  <div class="drag-btn">
                    <span>{{row.Sort}}</span>
                  </div>
                </template>
              </vxe-table-column>
              <vxe-table-column field="Stepdesc" title="步骤描述" :edit-render="{name: '$input', props: {type: 'text'}}"></vxe-table-column>
              <vxe-table-column field="Expectedresults" title="预期结果" :edit-render="{name: '$input', props: {type: 'text'}}" width="300"></vxe-table-column>
            </vxe-grid>
            <vxe-button type="text" style="margin-bottom: 20px; color: #2d8cf0" @click="addBz">添加步骤</vxe-button>
            <el-form-item label="备注">
              <wangeditor placeholder="请输入前置条件" v-model="formData.Remarks" style="width: 100%"></wangeditor>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属模块">
              <select-project-module data="URL" :column="[{ field: 'Name', title: '模块名称' }]" placeholder="请选择所属模块"
                                     v-model="formData.Moduleid" style="width: 100%"></select-project-module>
            </el-form-item>
            <el-form-item label="用例类型">
              <select-diction v-model="formData.Type" DictTypeCode="CASE_TYPE" placeholder = "请选择用例类型" style="width: 100%"></select-diction>
            </el-form-item>
            <el-form-item label="重要程度">
              <select-diction v-model="formData.Degree" DictTypeCode="CASE_ZYCD" placeholder = "请选择重要程度" style="width: 100%"></select-diction>
            </el-form-item>
            <el-form-item label="维护负责人">
<!--              <vxe-input placeholder="请选择维护负责人" v-model="formData.Name" style="width: 100%"></vxe-input>-->
              <select-project-team v-model="formData.Acceptid" :column="[{field: 'Userrealname'}]" :clearable="true"
                                   placeholder = "请选择维护负责人"
                                   :showValueShow="[]" style="width: 100%"></select-project-team>
            </el-form-item>
            <el-form-item label="版本">
              <el-input placeholder="请输入版本" v-model="formData.Version" style="width: 100%">
                <template slot="append">
                  <span @click="addVersion" style="cursor: pointer">+</span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="编号">
              <span>{{ formData.Id || '' }}</span>
            </el-form-item>
            <el-form-item label="状态">
              <select-diction v-model="formData.Status" DictTypeCode="CASE_STATUS" placeholder = "请选择状态" style="width: 100%"></select-diction>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
  </dialog-edit>
</template>

<script>
import dialogEdit from '@/components/element/dialogEdit'
import dymForm from '@/components/element/dymForm'
import wangeditor from '@/components/element/wangeditor/index';
import SelectDiction from "@/components/element/SelectDiction";
import SelectProjectTeam from "@/components/element/select/SelectProjectTeam";
import testCaseApi from "@/api/testCaseApi";
import SelectProjectModule from "@/components/element/select/SelectProjectModule";
import Sortable from 'sortablejs'

export default {
  name: "testCaseEdit",
  components: {
    dialogEdit,
    dymForm,
    wangeditor,
    SelectDiction,
    SelectProjectTeam,
    SelectProjectModule
  },
  props: {
    visible: Boolean,
    form: Object
  },
  data () {
    return {
      saveLoading: false,
      formData: {
        TestCaseStep: []
      },
      tableData: [],
      componentsr: [],
      formRules: {}
    }
  },
  computed: {
    dialogVisible: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    }
  },
  methods: {
    addVersion () {
      if (this.formData.Version) {
        this.$set(this.formData, 'Version', (Number(this.formData.Version) + 1).toString())
      } else {
        this.$set(this.formData, 'Version', '1')
      }
    },
    rowDrop () {
      this.$nextTick(() => {
        try {
          if (this.sortable1) this.sortable1.destroy()
        } catch (e) {}
        const xTable = this.$refs.grid
        this.sortable1 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
          handle: '.drag-btn',
          onEnd: ({ newIndex, oldIndex }) => {
            let b = JSON.parse(JSON.stringify(this.tableData))
            this.formData.TestCaseStep = xTable.getTableData().tableData
            const currRow = b.splice(oldIndex, 1)
            b.splice(newIndex, 0, currRow)
            // console.log(xTable.getTableData().tableData);
            // this.tableData = xTable.getTableData()
          }
        })
      })
    },
    async addBz() {
      const record = {
        Sort: 1
      }
      const $table = this.$refs.grid
      let data = $table.getTableData().tableData
      if (data.length > 0) {
        record.Sort = Math.max(...data.map(it => it.Sort)) + 1
      }
      const {row: newRow} = await $table.insertAt(record, -1)
      await $table.setActiveCell(newRow, 'Sort')
      this.formData.TestCaseStep = $table.getTableData().tableData
      console.log(this.formData.TestCaseStep);
      this.rowDrop()
    },
    save () {
      this.saveLoading = true
      testCaseApi.createCase(this.formData).then(res => {
        this.$message({ type: res.code === 1 ? 'success' : 'warning', message: res.message })
        if (res.code === 1) {
          this.dialogVisible = false
          this.$emit('getDataList')
        }
      }).finally(() => {
        this.saveLoading = false
      })
    },
    getData () {
      if (this.form.Id) {
        testCaseApi.getCaseById(this.form).then(res => {
          if (res) {
            this.formData = Object.assign(res, this.formData)
          }
        }).finally(() => {
          // this.tableLoading = false
        })
      }
    }
  },
  watch: {
    dialogVisible (n, o) {
      if (o && !n) {
        try {
          if (this.sortable1) this.sortable1.destroy()
        } catch (e) {}
        this.formData = {}
      } else if (!o && n) {
        this.formData = Object.assign(this.formData, this.form)
        this.getData()
        this.rowDrop()
      }
    }
  }
}
</script>

<style scoped lang="scss">
.formBox /deep/ .el-form-item__label {
  padding: 0;
}
</style>